var api = require("../config.js");
var app = getApp();

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function formatDateCN(dateStr) {
  let date = new Date(dateStr)
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()

  return year + '年' + formatNumber(month) + '月' + formatNumber(day) + '日'
}


function postData(url, data) {
  return request(url + ";JSESSIONID=" + wx.getStorageSync("JSESSIONID"), Object.assign({
    mobileLogin: true,
    __ajax: true
  }, data), {
    'Content-Type': 'application/x-www-form-urlencoded'
  }, "POST")
}

function getData(url, data) {
  return request(url, Object.assign({
    mobileLogin: true,
    __ajax: true
  }, data))
}

function request(url, data = {}, headers = {}, method = "GET") {
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: Object.assign({
        'X-BIZ-Token': wx.getStorageSync('token')
      }, headers),
      success: function(res) {
        if (res.statusCode == 200) {
          if (res.data.success) {
            resolve(res.data)
          } else {
            showErrorToast(res.data.msg)
          }
        } else {
          reject(res.errMsg);
        }
      },
      fail: function(err) {
        reject(err)
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/images/icon_error.png'
  })
}

module.exports = {
  getData,
  postData,
  formatTime,
  formatDateCN,
  request,
  redirect,
  showErrorToast

}